package ys.ewp.tool;

import java.io.IOException;
import java.util.Hashtable;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import flex.messaging.MessageBroker;
import flex.messaging.endpoints.Endpoint;

public class FlexDispatcher extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String BROKER_ID = "flex.messagebroker.id";
	private String brokerId;
	private Hashtable<String, String> cache;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		brokerId = config.getInitParameter(BROKER_ID);
		cache = new Hashtable<String, String>();
	}
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String path = req.getServletPath();
		String forward_uri = cache.get(path);
		if(forward_uri == null){
			forward_uri = this.getChannelURI(path, req);
			cache.put(path, forward_uri);
		}
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(forward_uri);
		rd.forward(req, resp);
	}
	
	private String getChannelURI(String path, HttpServletRequest req) throws ServletException{
		int pos1 = path.lastIndexOf('/');
		int pos2 = path.lastIndexOf('.');
		pos2 = pos2 == -1?path.length() : pos2;
		String channelId = path.substring(pos1 + 1, pos2);
		MessageBroker broker = MessageBroker.getMessageBroker(brokerId);
		if(broker == null){
			throw new ServletException("no MessageBroker named"+channelId);
		}
		Endpoint ep = broker.getEndpoint(channelId);
		if(ep == null){
			throw new ServletException("no endpoint found by id:"+channelId);
		}
		String channelURI = ep.getParsedUrl(req.getContextPath());
		if(channelURI.startsWith("/") == false){
			channelURI = "/" + channelURI;
		}
		return channelURI;
	}
}
